<?php
/*------------------------------------------------------------------
 | Software: APHP - A PHP TOP Framework
 | Site: https://aphp.top
 |------------------------------------------------------------------
 | (C)2020-2024 无念<24203741@qq.com>,All Rights Reserved.
 |-----------------------------------------------------------------*/
declare(strict_types=1);

namespace app\index\controller;

use aphp\core\Jump;

class Down
{
    use Jump;

    // 下载zip文件
    public function zip(string $type, string $file)
    {
        $file_path = ROOT_PATH . '/download/' . $type . '/' . $file . '.zip';
        if ($this->isDomain() && file_exists($file_path)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($file_path));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file_path));
            readfile($file_path);
            exit;
        }
        echo '405';
        exit;
    }

    /*
        public function zip(string $type, string $file)
    {
        if (!$this->isDomain()) {
            $this->error('请访问aphp.top指定页面进行下载');
        }
        $file_path = ROOT_PATH . '/download/' . $type . '/' . $file . '.zip';
        if (file_exists($file_path)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($file_path));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file_path));
            readfile($file_path);
            exit;
        }
        $this->error('文件不存在');
    }
    */

    public function isDomain(): bool
    {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $referer = parse_url($_SERVER['HTTP_REFERER']);
            return $referer['host'] == $_SERVER['HTTP_HOST'];
        }
        return false;
    }
}